# -*- coding: utf-8 -*-
"""
    author: Ye
    date: 2021/01/25 14:20
"""
from models.api import Book, Author
from marshmallow import fields
from marshmallow_sqlalchemy import ModelSchema, auto_field, SQLAlchemyAutoSchema
from marshmallow import validates
from marshmallow.exceptions import ValidationError
from extensions import db


class BookSchema1(SQLAlchemyAutoSchema):
    # author = fields.Nested(AuthorSchema())

    class Meta:
        model = Book


class AuthorSchema(SQLAlchemyAutoSchema):
    books = fields.Nested(BookSchema1(), many=True)
    books_count = fields.Method('get_books_count')

    class Meta:
        model = Author
        include_relationships = True  # 输出模型对象时同时对外键，是否也一并进行处理
        include_fk = True  # 序序列阶段是否也一并返回主键
        load_instance = True  # 反序列化阶段时，直接返回模型对象
        sql_session = db.session  # 数据库连接会话对象
        # fields= ["id","name",'create_time'] # 启动的字段列表
        # exclude = ["id", "name"]  # 排除字段列表

    def get_books_count(self, obj):
        return Book.query.filter_by(author_id=obj.id).count()


class BookSchema(SQLAlchemyAutoSchema):
    author = fields.Nested(AuthorSchema,required=False)

    # author_id = fields.Integer(required=True,error_messages={'required':'id必填'})

    class Meta:
        model = Book
        include_relationships = True  # 输出模型对象时同时对外键，是否也一并进行处理
        include_fk = True  # 序序列阶段是否也一并返回主键
        load_instance = True  # 反序列化阶段时，直接返回模型对象
        sql_session = db.session  # 数据库连接会话对象

    @validates('author_id')
    def validate_name(self, data, **kwargs):
        print(data)
        author = Author.query.filter_by(id=data).all()
        if author:
            pass
        else:
            raise ValidationError('主键不存在')
